package com.smbms.service.impl;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smbms.mapper.UserMapper;
import com.smbms.pojo.User;
import com.smbms.service.UserService;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User selectUserCodeExist(String userCode) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userCode", userCode).select("userCode");
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            return user;
        } else {
            return null;
        }
    }

    @Override
    public boolean add(User user) {
        return userMapper.insert(user) > 0;
    }

    @Override
    public User getUserById(String id) {
        return userMapper.getUserById(id);
    }

    public User login(String userCode, String userPassword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("userCode", userCode).select("userCode", "userPassword", "userName", "userRole", "id");
        User user = userMapper.selectOne(queryWrapper);
        if (user.getUserPassword().equals(userPassword)) {
            return user;
        } else {
            return user;
        }
    }

    public IPage<User> getUserList(String userName, Integer userRole, Integer pageNo, Integer pageSize) {
        Page<User> page = new Page<>(pageNo, pageSize);
        IPage<User> iPage = userMapper.selectUserPage(page,userName,userRole);
        return iPage;
    }

    @Override
    public boolean modify(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", user.getId());
        return userMapper.update(user, queryWrapper) > 0;
    }

    @Override
    public boolean deleteUserById(Integer id) {
        return userMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updatePwd(int id, String userPassword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        User user = new User();
        user.setUserPassword(userPassword);
        user.setModifyBy(id);
        user.setModifyDate(new Date());
        return userMapper.update(user, queryWrapper) > 0;
    }
}
